package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    // 统计营业额
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        // 存放从开始到结束的时间内的集合
        List<LocalDate> list = new ArrayList<>();

        list.add(begin);

        while(!begin.equals(end)) {
         // 日期计算，一天一天往后移
            begin = begin.plusDays(1);
            list.add(begin);
        }

        // 存放每天的营业额
        List<Double> turnoverLists =  new ArrayList<>();
        for(LocalDate date : list){
            // 查询date日期的营业额，营业额是指：状态为“已完成”的订单金额合计
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN); //获取当天开始的时间 00：00：00
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX); //获取当天结束的时间 23：59：59
            // select sum(amount) from orders where order_time > ? and order_time and status = 5
            Map map = new HashMap();
            map.put("begin", begintime);
            map.put("end", endtime);
            map.put("status", 5);
            Double turnover = orderMapper.sumAmountByDate(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverLists.add(turnover);
        }
        // 把每一天都用逗号分隔
        String dateList = StringUtils.join(list, ",");
        // 把每一天的营业额用逗号分开
        String turnoverList = StringUtils.join(turnoverLists,",");

        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(dateList);
        turnoverReportVO.setTurnoverList(turnoverList);
        // 查询数据库，获取营业额
        return turnoverReportVO;
    }

    // 用户统计
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 存放从开始到结束的时间内的集合
        List<LocalDate> datelists = new ArrayList<>();

        datelists.add(begin);

        while(!begin.equals(end)) {
            // 日期计算，一天一天往后移
            begin = begin.plusDays(1);
            datelists.add(begin);
        }

        // 存放新增用户数据 select count(id) from user where create_time > ? and create_time < ?
        List<Integer> newUserLists = new ArrayList<>();
        // 存放总用户数据 select count(id) from user where create_time < ?
        List<Integer> totalUserLists = new ArrayList<>();
        for (LocalDate date : datelists) {
            LocalDateTime begintime = LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date,LocalTime.MAX);

            Map map = new HashMap();
            map.put("end",endtime);
            // 总用户
            Integer totalUser = userMapper.sumUserByDate(map);

            map.put("begin",begintime);
            // 新增用户
            Integer newUser = userMapper.sumUserByDate(map);

            totalUserLists.add(totalUser);
            newUserLists.add(newUser);
        }
        // 用逗号分隔
        String datelist = StringUtils.join(datelists,",");
        String totalUserList = StringUtils.join(totalUserLists,",");
        String newUserList = StringUtils.join(newUserLists,",");

        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(datelist);
        userReportVO.setTotalUserList(totalUserList);
        userReportVO.setNewUserList(newUserList);
        return userReportVO;
    }

    // 订单统计
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        // 存放begin到end的天数
        List<LocalDate> datelists = new ArrayList<>();

        datelists.add(begin);
        while(!begin.equals(end)){
            // 日期计算
            begin = begin.plusDays(1);
            datelists.add(begin);
        }

        // 存放每天的订单总数
        List<Integer> orderCounntLists = new ArrayList<>();
        // 存放每天的有效订单数
        List<Integer> vailOrderCountLists = new ArrayList<>();

        // 遍历datelists的集合
        for (LocalDate date : datelists){
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);
            // 查询每天的订单总数 select count(id) from orders where order_time >? and order_time<?
            Integer orderCount = getOrderCount(begintime,endtime,null);
            orderCounntLists.add(orderCount);
            // 查询有效订单数 select count(id) from orders where order_time >? and order_time<? and status = 5
            Integer validOrderCount = getOrderCount(begintime,endtime,5);
            vailOrderCountLists.add(validOrderCount);
        }
        // 存放订单总数
        Integer totalOrderCount = 0;
        // 存放有效订单数
        Integer vailOrderCount = 0;
        // 计算订单总数
        for(Integer orderCount : orderCounntLists){
                totalOrderCount+=orderCount;
        }
        // 计算有效订单数
        for (Integer vailOrderCount1 : vailOrderCountLists){
            vailOrderCount+=vailOrderCount1;
        }
        // 计算订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = vailOrderCount.doubleValue() /  totalOrderCount;
        }
        // 用逗号隔开
        String datelist = StringUtils.join(datelists,",");
        String orderCountList = StringUtils.join(orderCounntLists,",");
        String vailOrderCountList = StringUtils.join(vailOrderCountLists,",");

        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(datelist);
        orderReportVO.setOrderCountList(orderCountList);
        orderReportVO.setValidOrderCountList(vailOrderCountList);
        orderReportVO.setOrderCompletionRate(orderCompletionRate);
        orderReportVO.setOrderCountList(orderCountList);
        orderReportVO.setValidOrderCount(vailOrderCount);
        return orderReportVO;
    }

    // 销量排名前10
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime  = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);

        List<GoodsSalesDTO> salesTop = orderMapper.getSalesTop(beginTime, endTime);
        List<String> names = salesTop.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");

        List<Integer> numbers = salesTop.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    // 导出数据报表
    public void exportBusinessData(HttpServletResponse response) {
        // 1. 查询数据库，获取营业数据 --- 查询最近30天的运营数据
        LocalDate dateBegin =  LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        // 查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin,LocalTime.MIN)
                ,LocalDateTime.of(dateEnd,LocalTime.MAX));
        // 2. 通过POI将数据写入Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            // 基于模板文件创建
            XSSFWorkbook excel = new XSSFWorkbook(in);
            // 获得标签页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            // 填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间:"+dateBegin+"至"+dateEnd);
            // 获得第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第五行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            // 3. 将Excel文件写入到HttpServletResponse中，返回给前端
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            // 关闭资源
            outputStream.close();
            excel.close();
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    // 查询订单数量
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end,Integer status){
        Map map = new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);

        return orderMapper.getCountByDate(map);
    }
}
